/**
 * Created by admin on 2017/9/27.
 */
define([
    "helpers/network",
    "models/orders",
    "models/logistic",
    "models/menu",
    "models/roles",
    "views/modules/popup",
    "views/modules/form",
    "views/modules/table",
    "views/modules/pager"
], function (Network, Orders, Logistic, Menu, Roles, PopupView, CommonForm, CommonTable, CommonPager) {
    var TYPE = "Role";
    var id = "";
    var tableId = id + "table";
    var treetable = id + "treetable";
    var windowId = id + "window";
    var formId = id + "form";
    var pagerId = id + "pager";
    var totalCountsId = id + "totalCounts";
    var pageIndex = 1, pageCounts;

    var onTableReady = function (page) {
        // var searchForm = $$(searchFormId).getValues();
        // var time = searchForm[dataRangeId]; //获取注册时间选择器对象
        var obj = {
            params: {},
            page: page || 1,
            sort: ["creationTime,desc"]
        };
        Network.ajax("/AdminGroupView.queryAll.query", obj, function (ret) {
            $$(tableId).clearAll();
            $$(tableId).parse(ret.data.content);
            CommonPager.refreshPager(page, ret.data.totalPages);
            $$(totalCountsId).setValue(ret.data.totalElements + "条数据, 共" + ret.data.totalPages + "页");
        });
        pageIndex = page ? page : 1
    };

    var updateSystemUser = function (roleId) {
        var obj = {
            params: {},
            sort: ["creationTime,desc"],
            all: true
        };
        Network.ajax("/BizView.queryAll.query", obj, function (ret) {

        });
    };

    var onSubmit = function (itemId) {
        if (!$$(formId).validate()) {
            webix.message("信息填写有误, 请仔细录入...");
            return
        }
        var itemValues = $$(formId).getValues();
        itemValues.lastModifyTime = new Date();
        var ajaxUrl = itemValues.id ? "/AdminGroupTransactor.update.command" :"/AdminGroupTransactor.create.command";
        var obj = {
            data: {
                id : itemValues.id,
                name: itemValues.rolename,
                remark: itemValues.remark,
                authorityIds: []
            }
        };
        $$(treetable).data.eachLeaf(0, function (each) {
            if (each.checked) {
                obj.data.authorityIds.push(each.id)
            }
        });
        Network.ajax(ajaxUrl, obj, function (ret) {
            closeWindow();
            onTableReady();
            // updateSystemUser(itemId);
        })
    };

    var onWindowReady = function (item) {

    };

    var closeWindow = function () {
        if ($$(windowId)) {
            $$(windowId).close();
        }
    };

    var queryAllToTree = function () {
        var obj = {
            params: {},
            sort: ["creationTime,desc"],
            all: true
        };
        Network.ajax("/BizView.queryAll.query", obj, function (ret) {

        });
    };

    var onTreetableReady = function (checkedItemIds) {
        Network.ajax("/AdminAuthorityView.queryAllToTree.query", {}, function (ret) {
            $$(treetable).parse(ret.data);
            $$(treetable).data.eachLeaf(0, function (eachLeaf) {
                if (_.indexOf(checkedItemIds,eachLeaf.id)!=-1) {
                    $$(treetable).checkItem(eachLeaf.id)
                }
            });
            // updateSystemUser(itemId);
        })
    };

    var showWindow = function (title, item) {
        item = item || {data: {}};
        PopupView(windowId, title, {
                rows: [{
                    view: "form", borderless: true, id: formId,
                    elements: [
                        {
                            label: "id", name: "id", view: "text", hidden:true,
                            required: true, value: item.id || ""
                        },
                        {name: "rolename", view: "text", label: "角色名", value: item.name || "", required: true},
                        {name: "remark", view: "text", label: "备注", value: item.remark || ""},
                        {
                            id: treetable, view: "treetable", name: "authorities",
                            threeState: true, select: "row", data: [],
                            ready: function () {
                                onTreetableReady(item.authorityIds)
                            },
                            columns: [
                                {
                                    id: "name", header: "权限", width: 250, fillspace: true,threeState:true,select: "row",
                                    template: "{common.treetable()} {common.treecheckbox()}  #name#"
                                },
                                {
                                    id: "remark", header: "备注", fillspace: true,
                                    template: function (obj) {
                                        return obj.code ? obj.code : ""
                                    }
                                }
                            ]
                        }
                    ]
                },
                    CommonForm.genSubmitButton(function () {
                        onSubmit(item.id)
                    })]

            },
            700, 700, function () {
                onWindowReady(item)
            }, closeWindow);
    };

    var genSearchFormUI = function () {
        return {
            view: "scrollview", scroll: "x",
            body: {
                id: "searchFormId", view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
                cols: [
                    {},
                    {
                        id: "keyWord", name: "keyWord", view: "text", fillspace: true, placeholder: "请输入商品名称进行查询",
                        on: {
                            onKeyPress: function (code) {
                                if (code !== 13) {
                                    return
                                }
                                onTableReady(1)
                            }
                        }
                    },
                    {
                        view: "button", label: "检索", width: 90, type: "form",
                        click: function () {
                            onTableReady(1)
                        }
                    }]
            }
        }
    };

    var genOperationFormUI = function () {
        return {
            view: "scrollview", scroll: "x",
            body: {
                view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
                cols: [
                    {view: "label", label: "操作"},
                    // {
                    //     view: "button", label: "导出文件", width: 90, disabled: true,
                    //     click: function () {
                    //         // getExportData()
                    //     }
                    // },
                    {
                        view: "button", label: "添加", width: 90,
                        // hidden: Authority.hasNoAuth("ADMIN_MGMT_ROLE_ADD"),
                        click: function () {
                            showWindow("新增")
                        }
                    },
                    {
                        view: "button", label: "修改", width: 90,
                        // hidden: Authority.hasNoAuth("ADMIN_MGMT_ROLE_MODIFY"),
                        click: function () {
                            var item = $$(tableId).getSelectedItem();
                            if (item) showWindow("修改", item)
                        }
                    },
                ]
            }
        }
    };

    var genDataTableUI = function () {
        return {
            id: tableId, view: "datatable", resizeColumn: true, select: "row", complexData: true,
            ready: onTableReady,
            columns: [
                {id: "roleName", header: "角色名", width: 250, template: "#name#"},
                {id: "remark", header: "备注", fillspace: true, template: "#remark#"},
                // CommonTable.genLastModifyTimeColumn()
            ],
            on: {
                onItemClick: function () {
                    // $$("btnPass").enable();
                    // $$("btnRejec").enable();
                },
                onItemDblClick: function (id) {
                    // if (Authority.hasNoAuth("SHOPPINGGOLD_ORDERS_LOGISTIC_INFO_ADD")) {
                    //     return
                    // }
                    // showPopupWindow("物流卡", this.getItem(id))
                }
            },
            data: []
        }
    };

    var genFooterUI = function () {
        return {
            cols: [
                CommonPager.genPagerUI(pagerId, pageIndex, pageCounts, onTableReady),
                CommonPager.genTotalCountsUI(totalCountsId), {}
            ]
        }
    };

    return {
        $ui: {
            padding: 10,
            rows: [
                // genSearchFormUI(),
                genOperationFormUI(),
                genDataTableUI(),
                genFooterUI()
            ]
        }
    };

});